using B.S.XZYData.Api.Wrter.Application.Command.AssemblyWorkOrder;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System.Transactions;
using System.Linq;

namespace B.S.XZYData.Api.Wrter.Application.Handler.AssemblyWorkOrder
{
    /// <summary>
    /// 删除装配工单处理器
    /// </summary>
    public class DeleteAssemblyWorkOrderHandler : IRequestHandler<DeleteAssemblyWorkOrderCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Domain.ZSHH.AssemblyWorkOrder> _assemblyWorkOrderRepo;
        private readonly IBaseRepository<AssemblyWorkOrderProductDetail> _productDetailRepo;
        private readonly ILogger<DeleteAssemblyWorkOrderHandler> _logger;

        public DeleteAssemblyWorkOrderHandler(
            IBaseRepository<Domain.ZSHH.AssemblyWorkOrder> assemblyWorkOrderRepo,
            IBaseRepository<AssemblyWorkOrderProductDetail> productDetailRepo,
            ILogger<DeleteAssemblyWorkOrderHandler> logger)
        {
            _assemblyWorkOrderRepo = assemblyWorkOrderRepo;
            _productDetailRepo = productDetailRepo;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(DeleteAssemblyWorkOrderCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();
            try
            {
                // 验证装配工单是否存在
                var existingWorkOrder = await _assemblyWorkOrderRepo.GetValue(request.Id);
                if (existingWorkOrder == null)
                {
                    res.Msg = "装配工单不存在";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    // 逻辑删除装配工单
                    existingWorkOrder.IsDeleted = true;
                    existingWorkOrder.Updator = request.Deleter;
                    existingWorkOrder.UpdatorDate = DateTime.Now;

                    var workOrderResult = await _assemblyWorkOrderRepo.UpdateAsync(existingWorkOrder);
                    if (workOrderResult <= 0)
                    {
                        res.Msg = "删除装配工单失败";
                        res.Code = ApiEnum.Fail;
                        return await System.Threading.Tasks.Task.FromResult(res);
                    }

                    // 逻辑删除关联的产品明细
                    var existingProductDetails = _productDetailRepo.GetAll()
                        .Where(x => !x.IsDeleted && x.WorkOrderId == request.Id)
                        .ToList();

                    if (existingProductDetails.Any())
                    {
                        foreach (var detail in existingProductDetails)
                        {
                            detail.IsDeleted = true;
                            detail.Updator = request.Deleter;
                            detail.UpdatorDate = DateTime.Now;
                            await _productDetailRepo.UpdateAsync(detail);
                        }
                    }

                    scope.Complete();
                    res.Data = (int)request.Id;
                    res.Code = ApiEnum.Success;
                    res.Msg = "删除装配工单成功";
                }

                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                _logger.LogError($"删除装配工单异常：{ex.Message}");
                res.Msg = "删除装配工单异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }
    }
} 